const mongoose = require('mongoose'),
	Schema = mongoose.Schema,
	bcrypt = require('bcrypt')

// 密码加密等级
const SALT_WORK_FACTOR = 10

let ObjectId = Schema.Types.ObjectId

const UserSchema = new Schema(
	{
		UserId: ObjectId,
		userName: { unique: true, type: String },
		password: String,
		createAt: { type: Date, default: Date.now() },
		lastLoginAt: { type: Date, default: Date.now() }
	},
	{
		collection: 'User'
	}
)

// 每次保存时进行加盐加密处理
UserSchema.pre('save', function(next) {
	bcrypt.genSalt(SALT_WORK_FACTOR, (err, salt) => {
		if (err) return next(err)

		bcrypt.hash(this.password, salt, (err, hash) => {
			if (err) return next(err)

			this.password = hash
			next()
		})
	})
})

UserSchema.methods = {
	comparePassword: (_password, password) => {
		return new Promise((resolve, reject) => {
			bcrypt.compare(_password, password, (err, isMatch) => {
				if (!err) resolve(isMatch)
				else reject(err)
			})
		})
	}
}

mongoose.model('User', UserSchema)
